const { get2faCode } = require('../2fa/2fa');

const checkEmail = async (page, email) => {
    const checkEmailBox = await page.locator("xpath=//input[@name='text']").all()
    console.log(checkEmailBox.length)
    if (checkEmailBox.length > 0) {
        console.log('需要验证邮箱')
        await checkEmailBox[0].fill(email);
        await page.locator("xpath=//button[@role='button']/div/span/span[text()='下一步']").click();
    }
}

const towfa = async (browser, page, tow_fa_url) => {
    const towfaBox = await page.locator("xpath=//input[@name='text']").all()
    console.log(towfaBox.length)
    if (towfaBox.length > 0) {
        console.log('需要验证2fa')
        const verify_code = await get2faCode(browser, tow_fa_url);
        await towfaBox[0].fill(verify_code);
        await page.locator("xpath=//button[@role='button']/div/span/span[text()='下一步']").click();
    }
}

const loginX = async (browser,page, user, pwd, email, tow_fa_url) => {
    // await page.goto('https:www.x.com', { timeout: 120000 });
    const loginButton = await page.getByTestId('loginButton').all()
    if (loginButton.length === 0) {
        console.log('已经登录')
        return;
    }
    await page.getByTestId('loginButton').click();
    await page.locator('label div').nth(3).click();
    await page.locator('label div').nth(3).fill(user);
    await page.getByRole('button', { name: 'Next' }).or(await page.getByRole('button', { name: '下一步' })).click()
    await page.waitForTimeout(5000);
//     await checkEmail(page, email) 
//     await page.waitForTimeout(5000);
//     await towfa(browser,page, tow_fa_url)
//     await page.waitForTimeout(5000);
//     await page.locator("xpath=//input[@name='password']").click();
//     await page.locator("xpath=//input[@name='password']").fill(pwd);
//     await page.getByTestId('LoginForm_Login_Button').click();
//     await page.waitForTimeout(5000);
//     await checkEmail(page, email) 
//     await page.waitForTimeout(5000);
//     await towfa(browser, tow_fa_url)
}

if (require.main === module) {
    (async () => {
        const { chromium } = require('playwright');
        const browser = await chromium.launch({ headless: false });
        const page = await browser.newPage();
        await loginX(browser, page, user='mingda96', pwd='wangmingda'); // 调用主函数
    })
}


module.exports = { loginX };